package top.jojoace.JPA.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class GenericAndJson {

    private static ObjectMapper mapper;

    @Autowired
    public void setMapper(ObjectMapper mapper){
        GenericAndJson.mapper = mapper;
    }

    public static <T> String objectToJson(T o){
        try {
            return GenericAndJson.mapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException("");
        }
    }

    public static <T> T jsonToObject(String str, TypeReference<T> typeReference){
        try {
            return GenericAndJson.mapper.readValue(str,typeReference);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException("");
        }
    }

    /**
     * 该方法存在问题，无法哪都TypeReference<T>的T，使得后续用Map代替
     * @param str
     * @return
     * @param <T>
     */
    public static <T> T jsonToObject2(String str){
        try {
            return GenericAndJson.mapper.readValue(str,new TypeReference<T>(){});
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException("");
        }
    }
}
